<?php

namespace app\admin\controller\user;

use app\admin\controller\Controllers;
use app\admin\model\user\UserNumber;
use app\admin\service\user\Info as InfoService;
use think\facade\Validate;

class Info extends Controllers
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(InfoService $service)
    {
        $get = $this->request->get();
        $this->validate($get, 'app\admin\validate\user\Info.index');
        $list = $service->indexPaginate($get);
        $config = config('field.user_number');
        $this->assign([
            'get' => $get,
            'list' => $list,
            'page' => $list->render(),
            'count' => $list->total(),
            'status' => $config['status']
        ]);
        return $this->fetch('user/info/index');
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param UserNumber $model
     * @return \think\Response
     */
    public function edit(UserNumber $model)
    {
        $config = config('field.user_number');
        $this->assign([
            'status' => $config['status'],
            'data' => $model
        ]);
        return $this->fetch('user/info/edit');
    }

    /**
     * 保存更新的资源
     *
     * @param  int  $id
     * @param InfoService $service
     * @return \think\Response
     */
    public function update(int $id, InfoService $service)
    {
        $put = $this->request->only(['mobile','number','status'], 'put');
        $put['id'] = $id;
        $this->validate($put, 'app\admin\validate\user\Info.update');
        if ( $service->save($id, $put) === false ) {
            return failed('编辑失败');
        }
        return success();
    }

    /**
     * 状态修改
     * @author zx
     * @date 2019-12-17
     * @return \think\Response
     */
    public function status(InfoService $service, UserNumber $model)
    {
        return $service->status($model);
    }

    /**
     * 检测手机号或账号是否唯一
     * @author zx
     * @date 2019-12-17
     * @return \think\Response
     */
    public function only(InfoService $service)
    {
        $get = $this->request->only(['id','mobile','number'], 'get');
        if ( ! get($get, 'mobile') && ! get($get, 'number') ) {
            return json(false);
        }
        $rules = [
            'id' => 'require|integer|>:0',
            'mobile' => 'mobile',
            'number' => 'integer|length:6,10'
        ];
        $v = Validate::make($rules, []);
        $result = $v->check($get);
        if ( ! $result ) {
            return json($result);
        }
        $bool = $service->only($get);
        return json($bool);
    }

}
